package com.jiubanqingchen.wish.plugin.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.jiubanqingchen.wish.kit.ExpressionKit;
import com.jiubanqingchen.wish.kit.WebSocketKit;
import com.jiubanqingchen.wish.plugin.easyexcel.json.WebSocketExcelJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author light_dust
 * @since 2021/5/14 20:52
 */
public class MapDataListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final Logger logger = LoggerFactory.getLogger(MapDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    private int index=0;//下标
    private int total = 0;//总数
    List<Map<Integer, String>> list = new ArrayList<>();

    /**
     * web socket id
     */
    private String socketId = null;

    public MapDataListener() {

    }

    public MapDataListener(String socketId) {
        this.socketId = socketId;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        if(index==0) WebSocketKit.sendMessageTo(new WebSocketExcelJson("开始读取数据>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"), socketId);
        index++;//我们默认第一次的时候index 为1 这样不用减来减去
        if(total==0) total=context.readSheetHolder().getApproximateTotalRowNumber();
        list.add(data);
        WebSocketKit.sendMessageTo(new WebSocketExcelJson(index,total, ExpressionKit.replaceBrackets("解析到一条数据,用户的姓名为：{}", data.get(1))), socketId);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        WebSocketKit.sendMessageTo(new WebSocketExcelJson("所有数据解析完成！"), socketId);
        logger.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        logger.info("{}条数据，开始存储数据库！", list.size());
        WebSocketKit.sendMessageTo(new WebSocketExcelJson(ExpressionKit.replaceBrackets("{}条数据，开始存储数据库！", list.size())), socketId);
        logger.info("存储数据库成功！");
        WebSocketKit.sendMessageTo(new WebSocketExcelJson(total,total,ExpressionKit.replaceBrackets("存储数据库成功！")), socketId);
    }
}
